﻿using System;

namespace org.nutilities.common
{
  public static class Extensions
  {
    public static void Append(this Response response, Response newResponse)
    {
      foreach (Status status in newResponse.StatusList)
      {
        response.Append(status);
      }
    }

    public static void Append(this Response response, Status status)
    {
      Status foundStatus = null;
      bool wasFound = false;
      foreach (Status candidateStatus in response.StatusList)
      {
        if (status.Identifier == candidateStatus.Identifier)
        {
          foundStatus = candidateStatus;
          wasFound = true;
        }
      }

      if (!wasFound)
      {
        response.StatusList.Add(status);
      }
      else
      {
        if (foundStatus.Level < status.Level)
          foundStatus.Level = status.Level;

        foreach (string message in status.Messages)
        {
          foundStatus.Messages.Add(message);
        }
      }

      if (response.Level < status.Level)
        response.Level = status.Level;
    }

    public static string ToString(this Response response)
    {
      string messages = String.Empty;

      foreach (Status status in response.StatusList)
      {
        foreach (string message in status.Messages)
        {
          messages += String.Format("{0} : {1}\\r\\n", status.Identifier, message);
        }
      }

      return messages;
    }
  }
}
